<template>
  <Dialog v-model="dialogVisible" title="导入表" width="800px">
    <!-- 搜索栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="数据源" prop="dataSourceConfigId">
        <el-select
          v-model="queryParams.dataSourceConfigId"
          class="!w-240px"
          placeholder="请选择数据源"
        >
          <el-option
            v-for="config in dataSourceConfigList"
            :key="config.id"
            :label="config.name"
            :value="config.id!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" />
          重置
        </el-button>
        <el-button @click="handleRefreshQuery">
          <Icon icon="ep:refresh" />
          刷新库表缓存
        </el-button>
      </el-form-item>
    </el-form>

    <el-alert
      title="已导入的表不再列出，若未列出需要的表，可以尝试点击 '刷新库表缓存' 按钮."
      type="warning"
      show-icon
      :closable="false"
    />

    <!-- 库表列表 -->
    <el-row>
      <el-table
        ref="dbTableRef"
        v-loading="dbTableLoading"
        :data="dbTableList"
        height="282px"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="表名称" prop="tableName" show-overflow-tooltip />
        <el-table-column label="表描述" prop="tableComment" show-overflow-tooltip />
      </el-table>
    </el-row>

    <!-- 操作 -->
    <template #footer>
      <el-button
        :disabled="selectedDbTableList.length === 0 || formLoading"
        type="primary"
        @click="handleImportTable"
      >
        导 入
      </el-button>
      <el-button @click="close">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as CodegenApi from '@/api/infra/codegen'
import * as DataSourceConfigApi from '@/api/infra/dataSourceConfig'
import { ref } from 'vue'
import { ElTable } from 'element-plus'

defineOptions({ name: 'InfraCodegenImportTable' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // dialog是否展示
const dbTableLoading = ref(false) // 数据源的加载中
const dbTableList = ref<CodegenApi.DatabaseTableVO[]>([]) // 数据源表列表
const dataSourceConfigList = ref<DataSourceConfigApi.DataSourceConfigVO[]>([]) // 数据源列表
const formLoading = ref(false) // 表单加载中标记

const queryParams = reactive({
  dataSourceConfigId: 0,
  tableName: undefined,
  tableComment: undefined,
  resetCache: undefined as boolean | undefined
})
const queryFormRef = ref()

const open = async () => {
  dialogVisible.value = true
  dataSourceConfigList.value = await DataSourceConfigApi.getDataSourceConfigList()
  if (dataSourceConfigList.value?.length) {
    queryParams.dataSourceConfigId = dataSourceConfigList.value[0].id!
    await getList()
  }
}
defineExpose({ open })

const close = () => {
  dialogVisible.value = false
  selectedDbTableList.value = []
}

const getList = async () => {
  dbTableLoading.value = true
  try {
    dbTableList.value = await CodegenApi.getDbTableList(queryParams)
    selectedDbTableList.value = []
  } finally {
    dbTableLoading.value = false
  }
}

// 保留handleQuery，以便后面需要改造为分页展示方式
const handleQuery = () => {
  queryParams.resetCache = undefined
  getList()
}

const resetQuery = async () => {
  // 不重置datasource
  queryParams.tableName = undefined
  queryParams.tableComment = undefined
  handleQuery()
}

const handleRefreshQuery = () => {
  queryParams.resetCache = true
  getList()
}

const dbTableRef = ref<InstanceType<typeof ElTable>>() // 表格的ref
const selectedDbTableList = ref<string[]>([]) // 表格选中的表名

const handleRowClick = (row) => {
  unref(dbTableRef)?.toggleRowSelection(row)
}

const handleSelectionChange = (selection) => {
  selectedDbTableList.value = selection.map((item) => item.tableName)
}

const emit = defineEmits(['success'])
const handleImportTable = async () => {
  const rows = unref(dbTableRef)?.getSelectionRows()
  if (!rows?.length) {
    message.warning('请先选择需要导入的表！')
    return
  }
  if (rows.length > 5) {
    message.warning('一次最多导入5张表！')
    return
  }
  formLoading.value = true
  try {
    await CodegenApi.createCodegenList({
      dataSourceConfigId: rows[0]?.dataSourceConfigId,
      tableNames: rows.map((item) => item.tableName)
    })
    message.success('导入成功')
    emit('success')
    close()
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped lang="scss"></style>
